package com.pku.smart.controller;

import com.alibaba.fastjson.JSON;
import com.pku.smart.constant.PayConstant;
import com.pku.smart.log.MyLog;
import com.pku.smart.service.SmartPayService;
import com.pku.smart.trade.service.IPaymentManagerService;
import com.pku.smart.trade.vopackage.VoReqPayScan;
import com.pku.smart.trade.vopackage.VoResPayScan;
import com.pku.smart.trade.vopackage.VoResTradePayment;
import com.pku.smart.vopackage.TradeResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 扫码支付
 * 用户通过手机扫描商户二维码
 */
@RestController
@RequestMapping(value = "/api")
public class PayScanController {
    private static final MyLog _log = MyLog.getLog(PayScanController.class);

    @Autowired
    SmartPayService payService;

    @Autowired
    IPaymentManagerService paymentManagerService;

    /**
     * 扫码支付
     * @param requestVo mchId channelId mchOrderNo totalAmount subject body notifyUrl clientIp device extra sign
     * @param bindingResult 校验必填字段 mchId channelId mchOrderNo totalAmount subject notifyUrl clientIp sign
     * @return 成功：返回二维码 失败：返回失败原因
     */
    @RequestMapping("/pay/create_order")
    public String scanPay(@ModelAttribute VoReqPayScan requestVo, BindingResult bindingResult) {
        TradeResultVo tradeResultVo = new TradeResultVo();

        _log.info("###### 开始接收商户统一扫码支付请求 ######");
        try {
            //参数校验
            payService.validateParams(requestVo,bindingResult);
            //调用服务
            VoResTradePayment payResultVo = paymentManagerService.scanPay(requestVo);
            //结果转换
            tradeResultVo.setRetCode(payResultVo.getRetCode());

            VoResPayScan resPayScan = (VoResPayScan) payResultVo.getRetData();
            if (PayConstant.TRADE_STATUS_SUCCESS.equalsIgnoreCase(payResultVo.getRetCode())){
                tradeResultVo.setMchId(resPayScan.getMchId());
                tradeResultVo.setMchOrderNo(resPayScan.getMchOrderNo());
                tradeResultVo.setCodeUrl(resPayScan.getCodeUrl());
            } else {
                tradeResultVo.setErrCode(resPayScan.getErrCode());
                tradeResultVo.setErrCodeDes(resPayScan.getErrCodeDes());
            }
        } catch (Exception e) {
            e.printStackTrace();
            tradeResultVo.setRetCode(PayConstant.TRADE_STATUS_FAILED);
            tradeResultVo.setErrCode(PayConstant.TRADE_STATUS_SYSTEM_ERROR_CODE);
            tradeResultVo.setErrCodeDes("系统异常：" + e.getMessage());
            _log.error(PayConstant.TRADE_STATUS_SYSTEM_ERROR_DESC,e);
        }

        String result = JSON.toJSONString(tradeResultVo);
        _log.info("打印结果：" + result);

        return result;
    }
}
